package com.fingersoft.dexload;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import androidx.multidex.MultiDex;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.fingersoft.im.R;

import java.lang.ref.WeakReference;

import cn.fingersoft.util.BuildConfigUtil;

/**
 * @author：jooper Email：jooperge@163.com
 * 描述：dex预加载， 仅适用于5.0以下系统
 * 修改历史:
 * <p>
 * 创建于： 2019-07-24
 */
public class PreLoadDexActivity extends Activity {

    private CustomVideoView splash_video;
    private View dex_preload_hint;
    private boolean isVideoSplashComplete = false;
    private boolean isMultiDexInstallComplete = false;
    private boolean useVideoInSplash = false;
    public static PreLoadDexActivity mInstance;
    private boolean isFirstResume = false;
    private Messenger messenger;
    private final long TIME_SELF_FINISH = 5000;
    private LoadDexTask dexTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        overridePendingTransition(0, 0);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mInstance = this;
        setContentView(R.layout.activity_multidex_preload);
        DexLoadUtil.getInstance().setIfNeedDexPreLoad(new WeakReference<>(this), true);

        dex_preload_hint = findViewById(R.id.dex_preload_hint);
        init2PlaySplash();

        Intent from = getIntent();
        messenger = from.getParcelableExtra("MESSENGER");

        /**
         * 启动预加载进程后首先清空最新版本标识，避免dex安装过程中强制关闭app后再次打开判断为非首次安装直接到主进程的splash页面出现同步安装dex的黑屏现象
         */
        LunchModeHelper.getInstance().clearLastVersion(this);

        dexTask = new LoadDexTask();
        dexTask.execute();
    }

    class LoadDexTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                MultiDex.install(getApplication());
                isMultiDexInstallComplete = true;
                Log.d("PreLoadDexActivity", "finish install");
                if (isVideoSplashComplete) {
                    messenger.send(new Message());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void o) {
            if (isMultiDexInstallComplete) {
                if (isVideoSplashComplete) {
                    finishDexPreLoadProcess(false);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirstResume) {
            isFirstResume = true;
        } else {
            init2PlaySplash();
        }
    }

    @Override
    protected void onDestroy() {
        if (null != dexTask) {
            dexTask.cancel(true);
            dexTask = null;
        }
        super.onDestroy();
    }

    private void init2PlaySplash() {
        if (isVideoSplashComplete) {
            return;
        }
        boolean extraUseVideo = getIntent().getBooleanExtra("useVideoInSplash", false);
        if (!extraUseVideo) {
            finish();
        } else {
            useVideoInSplash = BuildConfigUtil.INSTANCE.getBoolean("useVideoInSplash", false);
            if (!useVideoInSplash) {
                isVideoSplashComplete = true;
            }

            splash_video = findViewById(R.id.splash_video);
            if (useVideoInSplash) {
                try {
                    splash_video.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.splash_video));
                    splash_video.setOnCompletionListener((mp) -> {
                        dealWithVideoErrorOrComplete();
                    });
                    splash_video.setOnPreparedListener(mp ->
                        mp.setOnInfoListener((mp1, what, extra) -> {
                            if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                                splash_video.setBackgroundColor(Color.TRANSPARENT);
                                return true;
                            }
                            return false;
                        })
                    );
                    splash_video.setOnErrorListener((mp, what, extra) -> {
                        dealWithVideoErrorOrComplete();
                        Toast.makeText(PreLoadDexActivity.this, what + " - " + extra, Toast.LENGTH_SHORT).show();
                        return true;
                    });
                    splash_video.start();
                } catch (Exception e) {
                    dealWithVideoErrorOrComplete();
                    e.printStackTrace();
                }
            } else {
                dealWithVideoErrorOrComplete();
            }
        }
    }

    private void dealWithVideoErrorOrComplete(){
        isVideoSplashComplete = true;
        if (null != dex_preload_hint) {
            dex_preload_hint.setVisibility(View.VISIBLE);
        }
        if (isMultiDexInstallComplete) {
            finishDexPreLoadProcess(false);
        }
    }

    @Override
    protected void onPause() {
        if (null != splash_video) {
            splash_video.pause();
        }
        super.onPause();
    }

    @Override
    public void onBackPressed() {
    }

    private void finishDexPreLoadProcess(boolean instantly) {
        sendMsg2MainProcess();
        if (null != dex_preload_hint) {
            long time = instantly ? 0 : TIME_SELF_FINISH;
            dex_preload_hint.postDelayed(() -> {
                finish();
                System.exit(0);
            }, time);
        } else {
            finish();
            System.exit(0);
        }
    }

    /**
     * preload 所有逻辑通过，通知主进程继续
     */
    private void sendMsg2MainProcess() {
        try {
            LunchModeHelper.getInstance().markOpenApp(getApplication(), true);
            Message crashMessage = new Message();
            messenger.send(crashMessage);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
